package com.twu.biblioteca;

import com.twu.biblioteca.Entity.User;
import com.twu.biblioteca.Model.BookList;
import com.twu.biblioteca.Model.UserList;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BookCheckOutService implements Service {
    private String borrower = "LiuJing";
    private BookList bookList;
    private UserList userList;

    public BookCheckOutService(BookList bookList) {
        this.bookList = bookList;
    }

    public BookCheckOutService(BookList bookList, UserList userList) {
        this.bookList = bookList;
        this.userList = userList;
    }

    @Override
    public String getServiceDescription() {
        return "Checkout Book";
    }


    @Override
    public Menu getMenu() {
        return null;
    }

    public void doService() {
        if(userList.getLoginUser()!=null){
        System.out.println("Enter the book ID:");
        String bookID = getBookID();
        String result = checkOutBook(bookID);
        System.out.println(result);
        }
        else{
            LoginService loginService = new LoginService(userList);
            loginService.doService();
        }
    }

    public static String getBookID() {
        BufferedReader selection = new BufferedReader(new InputStreamReader(System.in));
        try {
            return selection.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "That book is not available";
    }

    public String checkOutBook(String bookID) {
        String result = "Thank you! Enjoy the book";
        if (isBookCanBeCheckOut(bookID)) {
            bookList.updateBookList(bookID, true, borrower);
        } else {
            result = "That book is not available";
        }
        return result;
    }

    private boolean isBookCanBeCheckOut(String bookID) {
        if (bookList.getBookList().containsKey(bookID) && !bookList.getBookList().get(bookID).isCheckOut()) {
            return true;
        }
        return false;
    }
}
